package mylogger;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.ArrayBlockingQueue;

public class MyAsyncFileAppender{
	
	private final int SIZE = 10000;
	
	private PrintWriter pw;
	private Thread adapterThread;
	
	private class QueueHandlerThread extends Thread{
		public void run(){
			String msg;
			while (!Thread.currentThread().isInterrupted()){
				synchronized (msgQueue) {
					while(msgQueue.size()==0){
						try {
							msgQueue.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			
				msg=msgQueue.poll();
				pw.println(msg);
				pw.flush();
			}
		}
	}
	
	private final String LOG_FILE = "logfile.txt";
	private static MyAsyncFileAppender currentInstance = null;
	
	private ArrayBlockingQueue<String> msgQueue = new ArrayBlockingQueue<String>(SIZE);
	
    private MyAsyncFileAppender(){
    	try {
    		pw  = new PrintWriter(new FileOutputStream(LOG_FILE, true));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
    	
    	adapterThread = new QueueHandlerThread();
    	adapterThread.setDaemon(true);
    	adapterThread.start();
    }

    public synchronized static MyAsyncFileAppender getInstance(){
    	if ( currentInstance == null ){
    		currentInstance = new MyAsyncFileAppender();
    	}
    	return currentInstance;
    }
    
    public void addMessage(String message){
    	synchronized (msgQueue) {
    		msgQueue.add(message);
			msgQueue.notifyAll();
		}
    	
    }
    
    
	
	
	public static String getDate(){
		DateFormat timeFormatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.UK);
		DateFormat weekFormatter = DateFormat.getDateInstance(DateFormat.WEEK_OF_YEAR_FIELD);
		Date today = new Date();
		return (weekFormatter.format(today)+" "+timeFormatter.format(today));
	}
	
	public void shutDown(){
		pw.close();
		adapterThread.interrupt();
	}
}